//
//  HSampleSkinDesignerWC.m
//  HMusicPlayer
//
//  Created by Hament on 14/10/13.
//  Copyright (c) 2014年 HJ. All rights reserved.
//



//skin 实体类
#define skinfolderpath  @"skinfolderpath"//-用日期命名
#define Gdisplayname    @"displayname"//- 和配置文件里面一样




//颜色 实体类

#define colorValue @"colorValue"
#define colorKeypath @"colorKeypath"

// colorValue - 4个浮点数 字符
// colorKeypath -
// displayname - 经过某个函数处理





#import "HSampleSkinDesignerWC.h"
#import "HCoreConfig.h"
#import "HskinManager.h"
#import "HcolorPicker.h"
#import "HMainWC.h"
#import "BFColorPickerPopover.h"

@interface HColorButton : NSButton

@property (nonatomic,strong)NSString * imagename;
@property (nonatomic,strong)NSString * imgColorStr;

@end


@implementation HColorButton

@end


@interface HSampleSkinDesignerWC ()<NSTextFieldDelegate,HcolorPickerDelegate>


@property (nonatomic,strong) HColorButton * lastClickBtn;

@end

@implementation HSampleSkinDesignerWC




static HSampleSkinDesignerWC * mainWc=nil;
+(HSampleSkinDesignerWC*)shareWc{
    
    @synchronized(self) {
        if (mainWc==nil) {
            mainWc=[[HSampleSkinDesignerWC alloc] initWithWindowNibName:@"HSampleSkinDesignerWC"];
        }
    }
    return mainWc;
    
}




- (void)windowDidLoad {
    [super windowDidLoad];
    
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    
    
    
    
    
    //指示颜色
    self.guidehlColor=[NSColor redColor];
    self.guidenorColor=[NSColor whiteColor];
    
    // popover
    self.popover=[[NSPopover alloc] init];
    self.popover.behavior=NSPopoverBehaviorSemitransient;
    self.popover.delegate=self;
    
    
    //设置双击
    [self.skinTv setDoubleAction:@selector(tableDoubleClickSkin:)];
    
    [self.colorTv setDoubleAction:@selector(tableDoubleClickColor:)];
    
    //menu bar上的按钮名字,对应skinplist
    self.menuNmlDataSource=@[@"icon_newsong_nml",@"icon_sequence_nml",@"icon_theme_nml",@"icon_store_nml",@"icon_setting_nml",@"icon_search_nml"];
    self.menuHltDataSource=@[@"icon_newsong_hlt",@"icon_sequence_hlt",@"icon_theme_hlt",@"icon_store_hlt",@"icon_setting_hlt",@"icon_search_hlt"];
    
    
    //添加imagecolor按钮
    self.iconDatasource=[NSMutableArray arrayWithCapacity:38];
    NSDictionary * imageColorDic=[[HCoreConfig shareConfig].currentSkinManager.currentConfigDic objectForKey:@"imageColor"];
    NSArray * allimagecolorkeys=[imageColorDic allKeys];
    allimagecolorkeys=[allimagecolorkeys sortedArrayUsingComparator:^(NSString * obj1 ,NSString* obj2) {
        //return [obj1.numStops compare:obj2.numStops options:NSNumericSearch]; }];//升序
        if ([obj1 compare:obj2]==NSOrderedAscending)
            return NSOrderedDescending ;
        else
            return NSOrderedAscending;
    }];

    NSUInteger iccount=allimagecolorkeys.count;
    CGFloat beginX=10;
    CGFloat beginY=20;
    CGFloat cWidth=40;
    CGFloat cHeigh=56;
    
    int clcount=0;
    //一共42个,如果以后
    for (int i=0; i<6; i++) {
         if (clcount==iccount) break;
        for (int j=0; j<9; j++) {
            
            
            
            HColorButton * button=[[HColorButton alloc] initWithFrame:NSMakeRect(beginX+j*(cWidth+10), beginY + i*(cHeigh+10), cWidth, cHeigh)];
            [button setAction:@selector(clickImgColorBtn:)];
            [button setTarget:self];
            //[button setBordered:YES];
            [button setButtonType:NSMomentaryChangeButton];
            [[button cell] setBezelStyle:NSTexturedSquareBezelStyle];
            [[button cell] setImagePosition:NSImageAbove];
            [[button cell] setImageScaling:NSImageScaleProportionallyUpOrDown];
            
            //icon name
            NSString * imagename=[allimagecolorkeys objectAtIndex:clcount];
            button.imagename=imagename;
            
            //色
            NSString * clorstr=[imageColorDic objectForKey:imagename];
            button.imgColorStr=clorstr;
            
//            NSImage * img=[[HCoreConfig shareConfig] getImageWithMainBundle:imagename];
//            [button setImage:img];
            
            if ([imagename hasSuffix:@"nml"]) {
                [button setTitle:@"nml"];
            } else if ([imagename hasSuffix:@"hlt"]) {
                [button setTitle:@"hlt"];
            } else {
              [button setTitle:@"-"];
            }
            
            [self.buttonView addSubview:button];
            [self.iconDatasource addObject:button];
            clcount++;
            if (clcount==iccount) break;
        }
        
    }
    
    //debugLog(@"self.iconDatasource:%d",self.iconDatasource.count);
    
    
    //1.获取skin
    
    
    NSArray * skins=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:skinFolder error:nil];
    
    self.colorDatasource=[NSMutableArray arrayWithCapacity:10];
    self.skinsDataSource=[NSMutableArray arrayWithCapacity:10];
    for (NSString * folderName in skins) {
        if (![folderName isEqualToString:@"currentskin"] && ![folderName isEqualToString:@".DS_Store"]) {
            NSString * path =[skinFolder stringByAppendingPathComponent:folderName];
            
            NSMutableDictionary * dic =[NSMutableDictionary dictionary];
            [dic setObject:path forKey:skinfolderpath];//path
            
            NSString * skinpath=[path stringByAppendingPathComponent:@"skinConfig.plist"];
            //name
            
            NSData *metaData = [NSData dataWithContentsOfFile:skinpath];
            NSError * error=nil;
            NSDictionary * sdic = [NSPropertyListSerialization propertyListWithData:metaData options:kCFPropertyListImmutable format:NULL error:&error];
            
            NSString * name=[sdic valueForKeyPath:@"string.skinName"];
            name=CHECKSTR(name);
            [dic setObject:name forKey:Gdisplayname];//path
            
            
            [self.skinsDataSource addObject:dic];
            
        }
    }
    
    
    
    
    [self.skinTv reloadData];
    
    
}




#pragma mark lazy
-(HcolorPicker*)colorPicker {
    if (!_colorPicker) {
        _colorPicker=[[HcolorPicker alloc] initWithNibName:@"HcolorPicker" bundle:nil];
        _colorPicker.delegate=self;
    }
    return _colorPicker;
}

#pragma mark-------
- (IBAction)addskin:(NSButton *)sender {
    
    //把默认皮肤配置复制一份
    
    NSString * folderName=[HCoreConfig generateSyncID];
    
    NSString * path =[skinFolder stringByAppendingPathComponent:folderName];
    
    NSMutableDictionary * dic =[NSMutableDictionary dictionary];
    [dic setObject:path forKey:skinfolderpath];//path
    
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString * skinpath=[path stringByAppendingPathComponent:@"skinConfig.plist"];
    NSString * defaultSkinpath=fileBundlePath(@"defaultSkinConfig", @"plist");

    
    [[NSFileManager defaultManager] copyItemAtPath:defaultSkinpath toPath:skinpath error:nil];
    //命名文件
    NSString * skinNamePath=[path stringByAppendingPathComponent:@"name.txt"];
    [@"default" writeToFile:skinNamePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    //name
    
    NSData *metaData = [NSData dataWithContentsOfFile:skinpath];
    NSError * error=nil;
    NSDictionary * sdic = [NSPropertyListSerialization propertyListWithData:metaData options:kCFPropertyListImmutable format:NULL error:&error];
    
    NSString * name=[sdic valueForKeyPath:@"string.skinName"];
    name=CHECKSTR(name);
    [dic setObject:name forKey:Gdisplayname];//path
    
    
    [self.skinsDataSource addObject:dic];
    [self.skinTv reloadData];
    
    
}

- (IBAction)deleteSkin:(NSButton *)sender {
    
    
    NSAlert* alert = [NSAlert alertWithMessageText:nil defaultButton:@"删除"alternateButton:@"取消" otherButton:nil informativeTextWithFormat:@"你要删除选中的项目吗?"];
    
    alert.alertStyle=NSCriticalAlertStyle;
    [alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(sheetDidEnd:resultCode:contextInfo:) contextInfo:nil];
 
}

- (IBAction)exportSkin:(NSButton *)sender {
    NSIndexSet * indexs=[self.skinTv selectedRowIndexes];
    
    
    if (indexs.count>0) {
        
        
        NSOpenPanel *panel = [NSOpenPanel openPanel];
        [panel setAllowsMultipleSelection:NO];
        [panel setCanChooseDirectories:YES];
        [panel setCanChooseFiles:NO];
        [panel setResolvesAliases:YES];
        [panel setPrompt:@"导出"];
        
        [HCoreConfig saveWithWindow:self.window panel:panel completionHandler:^(NSInteger result) {
            
            [panel orderOut:self];
            
            if (result != NSOKButton) {
                return;
            }
            
            
            NSURL *url = [[panel URLs] objectAtIndex:0];
            __block NSString * thepath=url.path;
            __block NSFileManager * fm=[NSFileManager defaultManager];
            
            [indexs enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
                
                NSDictionary * dic = [self.skinsDataSource objectAtIndex:idx];
                
                NSString * folderpath=dic[skinfolderpath];
                NSString * foldername=[folderpath lastPathComponent];
                NSString * despath=[thepath stringByAppendingPathComponent:foldername];
                
                [fm removeItemAtPath:despath error:nil];
                [fm copyItemAtPath:folderpath toPath:despath error:nil];
                
                
                
                
            }];
            
        }];
        
        
        
        
        
        
    }
    
    
}


- (IBAction)refreshSkin:(NSButton *)sender {
    
    
    
    
    NSInteger row=[self.skinTv selectedRow];
    // NSInteger crow=[self.tableV clickedRow];
    
    
    if (row!=-1) {
        
        
        NSDictionary * dic=[self.skinsDataSource objectAtIndex:row];
        NSString * folderpath=dic[skinfolderpath];
        NSString * skinpath=[folderpath stringByAppendingPathComponent:@"skinConfig.plist"];
        
        [[HCoreConfig shareConfig].currentSkinManager reloadWithConfigPath:skinpath];
        
        
        [[HMainWC shareWc] refreshSkin];
        
        //
        [[HMainWC shareWc].window makeKeyAndOrderFront:self];
        
        
    }
    
}


- (IBAction)backdefaultSkin:(NSButton *)sender{
    
    
    NSString * defaultSkinpath=fileBundlePath(@"defaultSkinConfig", @"plist");
    [[HCoreConfig shareConfig].currentSkinManager reloadWithConfigPath:defaultSkinpath];
    [[HMainWC shareWc] refreshSkin];
    //    [[HMainWC shareWc].window becomeKeyWindow];
    
    [[HMainWC shareWc].window makeKeyAndOrderFront:self];
    
    
    //
    
    
    
    
    
}



-(void)reloadColorWithSkinDic:(NSMutableDictionary*)skindic{
    
    
    
    // colorValue - 4个浮点数 字符
    // colorKeypath -
    // displayname - 经过某个函数处理
    [self.colorDatasource removeAllObjects];
    NSString * path=skindic[skinfolderpath];
    
    NSString * skinpath=[path stringByAppendingPathComponent:@"skinConfig.plist"];
    
    NSData *metaData = [NSData dataWithContentsOfFile:skinpath];
    NSError * error=nil;
    NSDictionary * sdic = [NSPropertyListSerialization propertyListWithData:metaData options:kCFPropertyListImmutable format:NULL error:&error];
    
    
    NSDictionary * colordic=[sdic objectForKey:@"color"];
    NSArray * allkeys=[colordic allKeys];
    allkeys=[allkeys sortedArrayUsingComparator:^(NSString * obj1 ,NSString* obj2) {
        //return [obj1.numStops compare:obj2.numStops options:NSNumericSearch]; }];//升序
        if ([obj1 compare:obj2]==NSOrderedAscending)
            return NSOrderedAscending;
        else
            return NSOrderedDescending;
    }];
    for (NSString * colork in allkeys) {
        
        NSString * cv=colordic[colork];
        NSMutableDictionary * cdic=[NSMutableDictionary dictionary];
        [cdic setObject:cv forKey:colorValue];
        
        NSString * displayname=[HskinManager getDisplayNameWithKey:colork];
        [cdic setObject:displayname  forKey:Gdisplayname];
        
        NSString * keypath=[@"color." stringByAppendingString:colork];
        [cdic setObject:keypath forKey: colorKeypath];
        
        [self.colorDatasource addObject:cdic];
        
    }
    
    [self.colorTv reloadData];
    
}


-(void)reloadImageIconWithSkinDic:(NSMutableDictionary*)skindic{


    NSUInteger count =[self.iconDatasource count];
    
    
    for (int i=0; i<count; i++) {
        HColorButton * btn=[self.iconDatasource objectAtIndex:i];

        NSImage * img=[[HCoreConfig shareConfig] getImageWithMainBundle:btn.imagename configDic:(NSDictionary*)self.currentSkinDic];
        
        [btn setImage:img];
        
        
        
    }


}

//统一设置所有icon的nml颜色
- (IBAction)setNml:(NSButton *)sender {
    

    

    
    
}

//统一设置所有icon的hlt颜色
- (IBAction)setallImgColor:(NSButton *)sender  {
    
    self.lastClickBtn=sender;
    //用人家的sdk
    [[BFColorPickerPopover sharedPopover] showRelativeToRect:sender.bounds ofView:sender preferredEdge:NSMinYEdge];
    [[BFColorPickerPopover sharedPopover] setTarget:self];
    [[BFColorPickerPopover sharedPopover] setAction:@selector(colorChanged:)];
    [[BFColorPickerPopover sharedPopover] setColor:[NSColor whiteColor]];
}



#pragma mark imagebutton
-(void)clickImgColorBtn:(HColorButton*)btn{
    self.lastClickBtn=btn;
    
    
    NSColor * color=[HskinManager getColorFromColorValue:btn.imgColorStr];
    
    //用人家的sdk
    [[BFColorPickerPopover sharedPopover] showRelativeToRect:btn.bounds ofView:btn preferredEdge:NSMinYEdge];
    [[BFColorPickerPopover sharedPopover] setTarget:self];
    [[BFColorPickerPopover sharedPopover] setAction:@selector(colorChanged:)];
    [[BFColorPickerPopover sharedPopover] setColor:color];
    
    

}


#pragma mark 双击
-(void)tableDoubleClickSkin:(id)object{
    NSInteger clickrow=[self.skinTv clickedRow];
    
    if (clickrow!=-1) {
        
        
        [[self window] endEditingFor:nil];
        NSTableCellView * cell=[self.skinTv viewAtColumn:0 row:clickrow makeIfNecessary:YES];
        
        [self.window makeFirstResponder:cell.textField];
        [cell.textField selectText:self];
        
        
        
    }
    
}

-(void)tableDoubleClickColor:(id)object{
    
    
    NSInteger clickrow=[self.colorTv clickedRow];
    
    if (clickrow!=-1) {
        
        NSMutableDictionary * cdic=[self.colorDatasource objectAtIndex:clickrow];
        NSColor * color=[HskinManager getColorFromColorValue:cdic[colorValue]];
        
        
        NSTableCellView * cell=[self.colorTv viewAtColumn:0 row:clickrow makeIfNecessary:YES];
        /*
         [self.popover close];
         [self.popover setContentViewController:self.colorPicker];
         [self.popover showRelativeToRect:cell.bounds ofView:cell preferredEdge:NSMinYEdge];
         //[self.window makeFirstResponder:self.searchTf];
         
         
         
         
         [self.colorPicker configWithColor:color];
         */
        
        
        //用人家的sdk
        [[BFColorPickerPopover sharedPopover] showRelativeToRect:cell.bounds ofView:cell preferredEdge:NSMinYEdge];
        [[BFColorPickerPopover sharedPopover] setTarget:self];
        [[BFColorPickerPopover sharedPopover] setAction:@selector(colorChanged:)];
        [[BFColorPickerPopover sharedPopover] setColor:color];
        
        
    }
    
    
}

- (IBAction)locateSkinFolder:(id)sender {
    
    
            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:skinFolder]]];
    
}

#pragma mark 高亮颜色指示
-(void)highlightColorwithRow:(NSInteger)row{

    NSArray * views=[self.guideView subviews];
    
    NSUInteger count=views.count;
    
    NSString * stringrow=[NSString stringWithFormat:@"%d",row+1];
    

        
        for (int i=0; i<count; i++) {
            NSView * view=[views objectAtIndex:i];
            
            if ([view isKindOfClass:[NSTextField class]]) {
                NSTextField * tf=(NSTextField*)view;
                if ([tf.stringValue isEqualToString:stringrow]) {
                    tf.backgroundColor=self.guidehlColor;
                } else {
                    tf.backgroundColor=self.guidenorColor;
                }
            }
        }
        

    


}

#pragma mark  ---------- tableview delegate (view based)--------

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    
    
    
    
    if ([tableView isEqualTo:self.skinTv]) {
        return [self.skinsDataSource count];
    }
    
    return [self.colorDatasource count];
}


- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
    
    
    
    if ([tableView isEqualTo:self.skinTv]) {
        return [self.skinsDataSource objectAtIndex:row];
    }
    
    return [self.colorDatasource objectAtIndex:row];
    
}





// This method is optional if you use bindings to provide the data
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
    //debugLog(@"loop row:%ld",row);
    
    NSDictionary * dic;
    NSTableCellView * cellView;
    
    
    //皮肤
    if ([tableView isEqualTo:self.skinTv]) {
        dic=[self.skinsDataSource objectAtIndex:row];
        
        
        
        cellView=[tableView makeViewWithIdentifier:@"skinCell" owner:tableView];
        cellView.textField.stringValue=dic[Gdisplayname];
        cellView.textField.delegate=self;
        
        
    }
    
    //颜色
    else {
        dic=[self.colorDatasource objectAtIndex:row];
        
        cellView=[tableView makeViewWithIdentifier:@"colorCell" owner:tableView];
        
        NSString * colorvalue=dic[colorValue];
        NSString * displayname=[NSString stringWithFormat:@"%d:%@",row+1,dic[Gdisplayname]] ;
        //NSString * colorkeypath=dic[colorkeypath];
        
        
        //显示颜色
        NSColor * color=[HskinManager getColorFromColorValue:colorvalue];
        //cellView.imageView.image.backgroundColor=color;
        
        cellView.textField.stringValue=displayname;//displayname;
        cellView.textField.backgroundColor=color;
        //colorcellView.textField.stringValue=@"ffffff";
    }
    
    
    
    return cellView;
    
}




- (void)tableViewSelectionDidChange:(NSNotification *)notification {
    
    
    NSTableView * tableview=[notification object];
    
    
    //皮肤
    if ([tableview isEqualTo:self.skinTv]) {
        
        
        NSIndexSet * selectindexset= [tableview selectedRowIndexes];
        //当点击空白行时
        if ([selectindexset count]!=0) {
            
            
            
            NSUInteger lastindex=[selectindexset lastIndex];
            NSMutableDictionary * skindic =[self.skinsDataSource objectAtIndex:lastindex];
            
            
            NSString * folderpath=skindic[skinfolderpath];
            NSString * skinpath=[folderpath stringByAppendingPathComponent:@"skinConfig.plist"];
            //name
            
            NSData *metaData = [NSData dataWithContentsOfFile:skinpath];
            NSError * error=nil;
            self.currentSkinDic = [NSPropertyListSerialization propertyListWithData:metaData options:kCFPropertyListMutableContainersAndLeaves format:NULL error:&error];
            
            [self reloadColorWithSkinDic:skindic];
            [self reloadImageIconWithSkinDic:self.currentSkinDic];
            
            
            
        } else {
            
            self.currentSkinDic=nil;
            [self.colorDatasource removeAllObjects];
            [self.colorTv reloadData];
        }
        
    }
    //
    else {
        
        [self highlightColorwithRow:[self.colorTv selectedRow]];
    }
    
    //    debugLog(@"skin select");
}

#pragma mark  ----------textfield delegate--------


- (void)controlTextDidBeginEditing:(NSNotification *)notification{
    
    //NSTextField * f=(NSTextField*)[notification object];
    
    
}


- (void)controlTextDidEndEditing:(NSNotification *)notification{
    
    
    NSTextField * f=(NSTextField*)[notification object];
    
    
    NSCharacterSet *  whitespaceSet= [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString * nTx=[f.stringValue stringByTrimmingCharactersInSet:whitespaceSet];
    
    
    
    //空串的话用回原来的name
    if ([nTx length]==0) {
        [self.skinTv reloadData];
        return;
    }
    
    
    
    //单击和双击,以及右击混用会引起问题,这里统一使用selectrow,禁用右击rename
    NSInteger row=[self.skinTv selectedRow];
    // NSInteger crow=[self.tableV clickedRow];
    
    
    if (row==-1) {
        return;
    }
    
    NSDictionary * dic=[self.skinsDataSource objectAtIndex:row];
    //debugLog(@"tag:%d ,value:%@",row,f.stringValue);
    
    if (dic) {
        
        NSTableCellView * selectedCell = [self.skinTv  viewAtColumn:0 row:row makeIfNecessary:YES];
        
        
        NSCharacterSet *  whitespaceSet= [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString * nTx=[f.stringValue stringByTrimmingCharactersInSet:whitespaceSet];
        
        
        NSString * name=dic[Gdisplayname];
        //没有变化
        if ([name isEqualToString:nTx]) {
            return;
        }
        
        
        [dic setValue:nTx forKey:Gdisplayname];
        selectedCell.textField.stringValue=nTx;//更改ui
        
        
        //读取 对应的plist
        NSString * folderpath=dic[skinfolderpath];

        [self.currentSkinDic setValue:nTx forKeyPath:@"string.skinName"];

        [HskinManager saveSkinWithDic:self.currentSkinDic toFolderPath:folderpath];
        
        
    }
    
    
    
}
#pragma mark  ---------- popover delegate --------
//当不同的window调用同一个popover冲突时
//- (NSWindow *)detachableWindowForPopover:(NSPopover *)popover {
//    return self.view.window;
//}


- (void)popoverWillClose:(NSNotification *)notification{
    
    NSPopover * pvr=(NSPopover*)[notification object];
    
    if ([pvr isEqual:self.popover]) {
        
    }
    
}


#pragma mark  ---------- NSTabview delegate--------
- (void)tabView:(NSTabView *)tabView didSelectTabViewItem:(NSTabViewItem *)tabViewItem{

    NSUInteger index=[tabView indexOfTabViewItem:tabViewItem];
    

    
    

}


#pragma mark  ---------- hcolorpicker delegate --------暂时没用到
- (void)selectColor:(NSString*)color{
    
    
    NSInteger row=[self.colorTv selectedRow];
    // NSInteger crow=[self.tableV clickedRow];
    
    
    if (row!=-1) {
        
        NSMutableDictionary * dic=self.colorDatasource[row];
        NSString * colorkey=dic[colorKeypath];
        
        //debugLog(@"color:%@",color);
        
        //NSString * thecolorValue=[HskinManager getColorStringValueWithColor:color];
        
        //改变数据源
        [self.currentSkinDic setValue:color forKeyPath:colorkey];
        [dic setObject:color forKey:colorValue];
        
        //
        [self.colorTv reloadData];
        
        
        //获取目录
        row=[self.skinTv selectedRow];
        dic=[self.skinsDataSource objectAtIndex:row];
        NSString * folderpath=dic[skinfolderpath];

        
        [HskinManager saveSkinWithDic:self.currentSkinDic toFolderPath:folderpath];
        
    }
    
}

- (void)colorDynamicChange:(NSColor*)color{
    
    
    NSInteger row=[self.colorTv selectedRow];
    // NSInteger crow=[self.tableV clickedRow];
    
    
    if (row!=-1) {
        
        // NSMutableDictionary * dic
        
        
        
    }
    
    
}



#pragma mark  ---------- bfcolorpicker  --------
- (void)colorChanged:(id)sender {
    
    NSColor * acolor=[BFColorPickerPopover sharedPopover].color;
    
    NSString * colorspacename=[acolor colorSpaceName];
    
    //    debugLog(@"colorSpaceName:%@",[acolor colorSpaceName]);
    //
    //    return;
    

    
    NSString* colorvalue;
    if ([colorspacename isEqualToString:@"NSCalibratedWhiteColorSpace"]) {
        colorvalue=[NSString stringWithFormat:@"%f,%f,%f,%f",acolor.whiteComponent,acolor.whiteComponent,acolor.whiteComponent,acolor.alphaComponent];
        
    } else if([colorspacename isEqualToString:@"NSCalibratedRGBColorSpace"] || [colorspacename isEqualToString:@"NSDeviceRGBColorSpace"]) {
        colorvalue=[NSString stringWithFormat:@"%f,%f,%f,%f",acolor.redComponent,acolor.greenComponent,acolor.blueComponent,acolor.alphaComponent];
    } else
        //例如:cmyk:NSCustomColorSpace
    {
        //cmyk转换为 rgba
        
        
        colorvalue=[HCoreConfig rgbaColorValueWithCmykColor:acolor];
 
    }
    //debugLog(@"colorvalue:%@",colorvalue);
    
    
    if([BFColorPickerPopover sharedPopover].userColorType && [[BFColorPickerPopover sharedPopover].userColorType isEqualToString:kBUseComplementColorType]) {
    
    colorvalue=[HCoreConfig complementaryColorrgbaColor:colorvalue];
    
    
    }
    
    
    
    
    
    
    NSUInteger index=[[self.tabView selectedTabViewItem].identifier integerValue];
    //icon image
    if (index==2) {

        if (self.lastClickBtn && self.currentSkinDic) {

            //1.如果点击的是某个icon按钮
            if([self.lastClickBtn isKindOfClass:[HColorButton class]]) {
            
            //改变数据源
            NSString * colorkey=[@"imageColor." stringByAppendingString:self.lastClickBtn.imagename];
            
           // debugLog(@"key:%@",colorkey);
            [self.currentSkinDic setValue:colorvalue forKeyPath:colorkey];
            self.lastClickBtn.imgColorStr=colorvalue;
            
            
            NSImage * img=[[HCoreConfig shareConfig] getImageWithMainBundle:self.lastClickBtn.imagename configDic:(NSDictionary*)self.currentSkinDic];
            
            [self.lastClickBtn setImage:img];
            
                
            }
            //2.如果点击的是全局设置按钮
            else  {
            
                
                NSDictionary * imageColorDic=[[HCoreConfig shareConfig].currentSkinManager.currentConfigDic objectForKey:@"imageColor"];
                NSArray * allimagecolorkeys=[imageColorDic allKeys];
                NSUInteger count =[allimagecolorkeys count];
                NSString * surfix=@"";
                
                switch (self.lastClickBtn.tag) {
                     //nml
                    case 99999991:
                    {
                    
                        surfix=@"nml";
                        for (int i=0; i<count; i++) {
                            HColorButton * hcb=[self.iconDatasource objectAtIndex:i];
                            
                            if ([hcb.imagename hasSuffix:surfix]) {
                                NSString * colorkey=[@"imageColor." stringByAppendingString:hcb.imagename];
                                [self.currentSkinDic setValue:colorvalue forKeyPath:colorkey];
                                hcb.imgColorStr=colorvalue;
                                
                                NSImage * img=[[HCoreConfig shareConfig] getImageWithMainBundle:hcb.imagename configDic:(NSDictionary*)self.currentSkinDic];
                                [hcb setImage:img];
                                
                            }
                            
                        }
                        
                        
                    }
                        break;
                    //hlt
                    case 99999992:
                    {
                        surfix=@"hlt";
                        for (int i=0; i<count; i++) {
                            HColorButton * hcb=[self.iconDatasource objectAtIndex:i];
                            
                            if ([hcb.imagename hasSuffix:surfix]) {
                                NSString * colorkey=[@"imageColor." stringByAppendingString:hcb.imagename];
                                [self.currentSkinDic setValue:colorvalue forKeyPath:colorkey];
                                hcb.imgColorStr=colorvalue;
                                
                                NSImage * img=[[HCoreConfig shareConfig] getImageWithMainBundle:hcb.imagename configDic:(NSDictionary*)self.currentSkinDic];
                                [hcb setImage:img];
                                
                            }
                            
                        }
                    }
                        break;
                      //menu nml
                    case 99999993: {
                        
                        
                        for (int i=0; i<count; i++) {
                            HColorButton * hcb=[self.iconDatasource objectAtIndex:i];
                            
                            for (NSString * str in self.menuNmlDataSource) {
                                if ([hcb.imagename isEqualToString:str]) {
                                    
                                    NSString * colorkey=[@"imageColor." stringByAppendingString:hcb.imagename];
                                    [self.currentSkinDic setValue:colorvalue forKeyPath:colorkey];
                                    hcb.imgColorStr=colorvalue;
                                    
                                    NSImage * img=[[HCoreConfig shareConfig] getImageWithMainBundle:hcb.imagename configDic:(NSDictionary*)self.currentSkinDic];
                                    [hcb setImage:img];
                                    
                                }

                            }

                            
                        }
                        
                    }
                        break;
                        //menu hlt
                    case 99999994: {
                        
                        for (int i=0; i<count; i++) {
                            HColorButton * hcb=[self.iconDatasource objectAtIndex:i];
                            
                            for (NSString * str in self.menuHltDataSource) {
                                if ([hcb.imagename isEqualToString:str]) {
                                    
                                    NSString * colorkey=[@"imageColor." stringByAppendingString:hcb.imagename];
                                    [self.currentSkinDic setValue:colorvalue forKeyPath:colorkey];
                                    hcb.imgColorStr=colorvalue;
                                    
                                    NSImage * img=[[HCoreConfig shareConfig] getImageWithMainBundle:hcb.imagename configDic:(NSDictionary*)self.currentSkinDic];
                                    [hcb setImage:img];
                                    
                                }
                                
                            }
                            
                            
                        }
                        
                    }
                        break;
                    default:
                        break;
                }
                
                
                
                
  
            
            }
            
            
            //写回文件
            NSUInteger row=[self.skinTv selectedRow];
            NSDictionary* dic=[self.skinsDataSource objectAtIndex:row];
            NSString * folderpath=dic[skinfolderpath];
            
            [HskinManager saveSkinWithDic:self.currentSkinDic toFolderPath:folderpath];
            
           
            
        }
 
    }
    //颜色
    else if (index==1){

    NSInteger row=[self.colorTv selectedRow];
    // NSInteger crow=[self.tableV clickedRow];
    
    
    if (row!=-1) {
        
        NSMutableDictionary * dic=self.colorDatasource[row];
        NSString * colorkey=dic[colorKeypath];
        
        //debugLog(@"color:%@",colorvalue);
        
        //NSString * thecolorValue=[HskinManager getColorStringValueWithColor:color];
        
        //改变数据源
        [self.currentSkinDic setValue:colorvalue forKeyPath:colorkey];
        [dic setObject:colorvalue forKey:colorValue];
        
        //
        [self.colorTv reloadData];
        
        
        row=[self.skinTv selectedRow];
        dic=[self.skinsDataSource objectAtIndex:row];
        NSString * folderpath=dic[skinfolderpath];

        [HskinManager saveSkinWithDic:self.currentSkinDic toFolderPath:folderpath];
        
    }
    }
    
    
     [[BFColorPickerPopover sharedPopover] close];
}




#pragma mark  ----------alertsheet delegate-------
- (void)sheetDidEnd:(NSWindow *)sheet resultCode:(NSInteger)resultCode contextInfo:(void *)contextInfo {
    
    
    if ([sheet isKindOfClass:[NSAlert class]]) {
        /*
         NSAlert* alert= (NSAlert*)sheet;
         NSString * message=alert.informativeText;
         //debugLog(@"message:%@",message);//标题
         */
        if (resultCode == NSAlertDefaultReturn) {
            NSIndexSet * indexs=[self.skinTv selectedRowIndexes];
            
            
            if (indexs.count>0) {
                
                
                [indexs enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
                    NSDictionary * dic=self.skinsDataSource[idx];
                    NSString * folderpath=dic[skinfolderpath];
                    [[NSFileManager defaultManager] removeItemAtPath:folderpath error:nil];
                    
                    
                }];
                
                [self.skinsDataSource removeObjectsAtIndexes:indexs];
                [self.skinTv removeRowsAtIndexes:indexs withAnimation:NSTableViewAnimationEffectNone];
                [self.skinTv reloadData];
                
            } else {
                
                self.currentSkinDic=nil;
            }
            
        } else if (resultCode ==NSAlertAlternateReturn){
            debugLog(@"cancel");
            
        } else if(resultCode ==NSAlertOtherReturn){
            
        }
    }
    
    
    
    
}



@end
